package org.jfinanceobserver.utillities;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * This class is the CVS parser
 *
 * $Author: r78v10a07@gmail.com $ $LastChangedDate: 2013-02-11 13:03:43 +0000 (Mon, 11 Feb 2013) $ $LastChangedRevision: 2 $
 *
 * @since Feb 8, 2013
 */
public class CVSParser {

    /**
     * Parse the CVS format from the line
     *
     * @param csvLine the line in CVS format
     * @return a string array with the fields
     */
    public static String[] parse(String csvLine) {
        int size;
        final Pattern csvPattern = Pattern.compile("\"([^\"]*)\"|(?<=,|^)([^,]*)(?:,|$)");
        ArrayList<String> allMatches = new ArrayList<>();
        Matcher matcher = csvPattern.matcher(csvLine);
        String match;
        while (matcher.find()) {
            match = matcher.group(1);
            if (match != null) {
                allMatches.add(match);
            } else {
                allMatches.add(matcher.group(2));
            }
        }

        size = allMatches.size();
        if (size > 0) {
            return allMatches.toArray(new String[size]);
        } else {
            return new String[0];
        }
    }
}
